import time
from airtest.core.api import *
from apicore.PocoApi import PocoApi
from base_page.phone_home.Phone_Home import Phone_Home


class IconSettings(PocoApi):
    def __init__(self):
        super().__init__()
        self.phone_home = Phone_Home()
    def __del__(self):
        super().__del__()
    # 进入一键安装
    def enter_page(self):
        self.phone_home.icon_settings()

    # 恢复出厂设置
    def reset_factory(self):
        time.sleep(5)
        self.enter_page()
        self.phone_home.poco_click(text="恢复出厂")
        try:
            # 等待图像出现
            queren = wait(
                Template(self.base_path + "/images/cloudphonehome/" + "queren.png", record_pos=(0.168, 0.22),
                         resolution=(1080, 2340)), timeout=5, interval=0.5)
            # 点击找到的图像
            touch(queren)
        except Exception as e:
            print(f"获取确认按钮失败：{e}")
            log(f"获取确认按钮失败：{e}")
        self.wait_reset_status()

    # 重启云机
    def restart_cloudphone(self):
        self.enter_page()
        time.sleep(5)
        self.phone_home.poco_click(text="重启云机")
        try:
            # 等待图像出现
            queren = wait(
                Template(self.base_path + "/images/cloudphonehome/" + "queren.png", record_pos=(0.168, 0.22),
                         resolution=(1080, 2340)), timeout=5, interval=0.5)
            # 点击找到的图像
            touch(queren)
        except Exception as e:
            print(f"获取确认按钮失败：{e}")
            log(f"获取确认按钮失败：{e}")
        self.wait_restart_status()

    # 文件上传
    def file_upload(self,filetype, appname):
        self.enter_page()
        time.sleep(5)
        self.phone_home.poco_click(text="文件上传")
        self.upload(filetype=filetype, appname=appname)
        self.upload_app_status()
        # 点击页面返回按钮
        self.phone_home.poco_click("android.widget.TextView")
        self.phone_home.poco_click("android.widget.TextView")
        time.sleep(6)
        # 进入云机
        self.phone_home.enter_the_cloud_machine()
        # 检查方法
        self.issucessppinstall(appname)
        self.exit_cloudin()

    # 恢复出厂设置的判断
    def wait_reset_status(self):
        status_element = self.poco(resourceId="com.unicom.cloudphone:id/tv_status")
        # 等待 "恢复出厂设置中" 状态
        start_time = time.time()
        while time.time() - start_time < 30:
            if status_element.exists() and status_element.get_text() == "恢复出厂设置中":
                print("云机正在恢复中")
                break
            time.sleep(1)
        else:
            print("云机状态失败")

        # 等待 "运行中" 状态
        start_time = time.time()
        while time.time() - start_time < 60:
            status_element = self.poco(resourceId="com.unicom.cloudphone:id/tv_status")
            if status_element.exists() and status_element.get_text() == "运行中":
                print("云机恢复成功")
                break
            time.sleep(1)
        else:
            print("云机恢复失败")

    # 重启云机状态的判断
    def wait_restart_status(self):  ##重启云机状态正常
        status_element = self.poco(resourceId="com.unicom.cloudphone:id/tv_status")

        # 等待 "重启中" 状态
        start_time = time.time()
        while time.time() - start_time < 30:
            if status_element.exists() and status_element.get_text() == "重启中":
                print("云机正在重启中")
                break
            time.sleep(1)
        else:
            print("云机状态失败")

        # 等待 "运行中" 状态
        start_time = time.time()
        while time.time() - start_time < 60:
            if status_element.exists() and status_element.get_text() == "运行中":
                print("云机重启成功")
                break
            time.sleep(1)
        else:
            print("云机重启失败")

    # 上传动作
    def upload(self,filetype=None, appname=None):
        try:
            # 等待图像出现
            wait(Template(self.base_path + "/images/cloudphonehome/" + "文件上传home.png", record_pos=(0.008, -0.831),resolution=(1080, 2340)), timeout=5, interval=0.5)
        except Exception as e:
            print(f"文件上传为失败，错误信息：{e}")
            log(f"文件上传为失败，错误信息：{e}")
        allowed_file_types = ['app', 'picture', 'file']
        if filetype not in allowed_file_types:
            raise ValueError(f"Invalid file type: {filetype}")
        elif filetype == 'app':
            self.phone_home.poco_click(text="应用")
            for i in appname:
                self.phone_home.poco_click_name_test("com.unicom.cloudphone:id/appName", text=i)
            try:
                # 等待图像出现
                wenjianshangchuan = wait(
                    Template(self.base_path + "/images/cloudphonehome/" + "文件上传按钮.png", record_pos=(0.323, 0.931),
                             resolution=(1080, 2340)), timeout=5, interval=0.5)
                # 点击找到的图像
                touch(wenjianshangchuan)
                # self.upload_app_status()
                # self.issucessppinstall(appname)
                # self.exit_cloudin()
            except Exception as e:
                print(f"文件上传应用失败，错误信息：{e}")
                log(f"文件上传应用失败，错误信息：{e}")
        elif filetype == 'picture':
            self.phone_home.poco_click(text="图片")
        else:
            self.phone_home.poco_click(text="文件")

    # 上传应用状态
    def upload_app_status(self):

        for i in range(120):
            element = self.poco(name="com.unicom.cloudphone:id/upload_status")
            time.sleep(1)
            if element.exists() and element.get_text() == "等待中":
                print("等待中")
                continue
            if element.exists() and element.get_text() == "推送到云机中...":
                print("推送到云机中...")
                continue
            if element.exists() and element.get_text() == "推送完成":
                print("应用上传成功")
                break
            if element.exists() and element.get_text() == "推送异常,请检查应用文件":
                print("推送异常,请检查应用文件")
                break

        # start_time = time.time()
        # while time.time() - start_time < 300:
        #     if element.exists() and element.get_text() == "推送异常,请检查应用文件":
        #         print("上传应用失败")
        #         break
        # else:
        #     print("应用上传成功")

        # 进入云机
    def enter_the_cloud_machine(self):
        self.phone_home.poco_click(text="进入云机")
        try:
            # 等待图像出现
            quxiao = wait(Template(self.base_path + "/images/cloudphonehome/" + "quxiao.png", record_pos=(0.148, 0.146),
                             resolution=(1080, 2340)), timeout=5, interval=0.5)
                # 点击找到的图像
            touch(quxiao)
        except Exception as e:
            print(f"进入云机失败，错误信息：{e}")
            log(f"进入云机失败，错误信息：{e}")


    # 退出云机
    def exit_cloudin(self):  ##退出云机
        self.phone_home.poco_click("com.unicom.cloudphone:id/iv_more")
        self.phone_home.poco_click(text="退出云手机")

    # 向左复位+
    def resetcloudphonein(self):
        for i in range(1, 5):
            swipe((100, 500), (800, 500))

    ##向右边滑动五页寻找指定图片
    def findcloudinpicture(self, picturepath):
        flag = 0
        for i in range(1, 5):
            if not exists(Template(picturepath)):
                swipe((1000, 400), (400, 400))
            else:
                print(f'******已经找到{picturepath}')
                flag = 1
                break
        self.resetcloudphonein()
        return flag

    # 公共方法判断是否安装成功
    def issucessppinstall(self, appnames):  ##公共方法判断是否安装成功
        picture_rootpath = self.base_path + "/images/cloudphonehome/"
        for appname in appnames:
            picturepath = os.path.join(picture_rootpath, f'{appname}.png')
            state = self.findcloudinpicture(picturepath)
            try:
                if state == 0:
                    print(f'{appname}安装失败')
                if state == 1:
                    print(f'{appname}安装成功')
            except Exception as e:
                print(f"安装失败，错误信息：{e}")